<?php
/**
 * Created by Engineer CuiLiwu.
 * Project: deal.
 * Date: 2018/4/24-11:27
 * License Hangzhou orce Technology Co., Ltd. Copyright © 2018
 */

namespace App\Console\Commands;

use App\Events\OrderCancelEvent;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Routing\Router;
use Illuminate\Support\Arr;
use Illuminate\Routing\Route;
use Illuminate\Support\Str;
use App\Repository\Models\OrdersCrontab;
use App\Events\OrderAffirmEvent;


class OrdersCrontabCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'crontab:orders';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单超时自动确认、订单超时自动取消';


    protected $ordersCrontab_repo;

    /**
     * Execute the console command.
     * TODO 自动确认订单执行函数
     * @return mixed
     */
    public function handle()
    {
        //订单自动取消
        $this->orderCancel();

        //订单自动确认收货
        $this->orderAffirm();
    }

    /**
     * 不使用事务，忽略异常
     * @return bool
     */
    private function orderCancel()
    {
        $time = date('Y-m-d H:i:s', time());
        // 获取 [ 超时且未确认 ] 的订单信息 @table orders_crontabs
        $orders_data = OrdersCrontab::query()
            ->where('status', OrdersCrontab::STATUS_NONE)
            ->where('type', OrdersCrontab::TYPE_CANCEL)
            ->where('expired_at', '<=', $time)
            ->get();
        $orders = $orders_data ? $orders_data->toArray() : [];

        foreach ($orders as $k => $ordersCrontab) {
            try {
                // 修改订单状态 && 通知银行放款 && 修改 @table orders_crontabs 状态为已确认
                $confirmEvent = event(new OrderCancelEvent(['order_id' => $ordersCrontab['order_id']]));
            } catch (\Exception $e) {
            }
        }

    }

    /**
     * 不使用事务，忽略异常
     * @return bool
     */
    private function orderAffirm()
    {
        $time = date('Y-m-d H:i:s', time());
        // 获取 [ 超时且未确认 ] 的订单信息 @table orders_crontabs
        $orders_data = OrdersCrontab::query()
            ->where('status', OrdersCrontab::STATUS_NONE)
            ->where('type', OrdersCrontab::TYPE_AFFIRM)
            ->where('expired_at', '<=', $time)
            ->get();
        $orders = $orders_data ? $orders_data->toArray() : [];

        foreach ($orders as $k => $ordersCrontab) {
            try {
                // 修改订单状态 && 通知银行放款 && 修改 @table orders_crontabs 状态为已确认
                $confirmEvent = event(new OrderAffirmEvent(['order_id' => $ordersCrontab['order_id']]));
            } catch (\Exception $e) {
            }
        }
    }

}
